from flask import Blueprint, request, send_from_directory
from flask_cors import CORS
import random
import json
import time
import hashlib

from user.model import User
from order.model import db
from order.model import Order
from order.model import Deliver
from order.model import Print
from user.model import Address
from file.model import File
from swiper.model import Swiper
from activity.model import Activity, Checkin

from admin.model import Admin

from datetime import datetime
from database import R

admin_blueprint = Blueprint('admin', __name__)
CORS(admin_blueprint, resources=r'/.*', supports_credentials=True,
     allow_headers=['Content-Type', 'token', 'Access-Control-Allow-Credentials'], intercept_exceptions=False)


def getEid():
    eid = R.get(request.headers.get('token'))
    if eid is None:
        return None
    else:
        return eid


@admin_blueprint.before_request
def before_eq():
    if request.path == '/admin/login' or request.path.find('/admin/files') >= 0:
        pass
    elif request.method != 'OPTIONS':
        if getEid() is None:
            return {
                       'errmsg': 'token expired'
                   }, 401


@admin_blueprint.route('/login', methods=['POST'])
def login():
    admin = Admin.query.filter(Admin.eid == request.json.get('user'),
                               Admin.password == request.json.get('pass')).first()
    if admin is None:
        return {
                   'errmsg': '用户名或密码错误'
               }, 201
    else:
        r = random
        token = (str(r.randint(10000, 99999)) + str(time.time_ns())).encode('utf-8')
        token = 'admin_' + hashlib.md5(token).hexdigest()
        R.set(token, admin.eid, ex=259200)
        return {
                   'userinfo': {
                       'eid': str(admin.eid),
                       'ename': admin.name,
                       'isadmin': str(admin.isadmin),
                       'token': token
                   }
               }, 200


@admin_blueprint.route("/userinfo", methods=['GET', 'POST'])
def userinfo():
    users = User.query.all()
    userlist = []
    genderlist = {0: '未知', 1: '男', 2: '女'}
    for user in users:
        userlist.append({
            'id': str(user.id),
            'money': user.money,
            'nickname': user.nickName,
            'name': user.realname,
            'gender': genderlist[user.gender],
            'phone': user.phone,
            'school': user.school,
            'xuehao': user.xuehao,
            'reminder': '开' if user.reminder == 1 else '关'
        })
    return {
               'userinfo': userlist
           }, 200


@admin_blueprint.route('/userlist', methods=['GET'])
def userlist():
    if request.method == 'GET':
        users = User.query.all()
        userlist = []
        for user in users:
            userlist.append({
                'id': user.id,
                'name': user.realname
            })
        return {
                   'userlist': userlist
               }, 200


@admin_blueprint.route('/addmoney', methods=['POST'])
def addmoney():
    if request.method == 'POST':
        uid = request.json.get('id')
        print(uid)
        money = request.json.get('addmoney')
        user = User.query.filter_by(id=uid).first()
        user.money = user.money + int(money)
        db.session.commit()

        order = Order(userid=uid, type='recharge', desca='', descb='',
                      status=2, time=datetime.now(), money=request.json.get('addmoney'), eid=getEid())  # 这里eid以后要改
        db.session.add(order)
        db.session.commit()
        return {
                   'id': uid,
                   'money': user.money
               }, 200


@admin_blueprint.route('/orderdetail', methods=['GET'])
def orderdetail():
    if request.method == 'GET':
        orders = Order.query.filter_by(status=2).order_by(Order.id.desc()).all()
        order_list = []

        for order in orders:
            user = User.query.filter_by(id=order.userid).first()
            ord_str = '-'
            if order.type == 'deliver' or order.type == 'print':
                ord_str = order.desca
            staff = '-'
            admin = Admin.query.filter_by(eid=order.eid).first()
            if admin is not None:
                staff = admin.name
            order_list.append({
                'id': str(order.id),
                'type': order.type,
                'name': user.realname,
                'userid': str(user.id),
                'time': order.time.strftime('%Y年%m月%d日 %H:%M:%S'),
                'order': ord_str,
                'staff': staff,
                'money': str(order.money)
            })
    return {
               'orderdetail': order_list
           }, 200


@admin_blueprint.route('/orderstatus', methods=['POST'])
def order_status():
    if request.method == 'POST':
        method = request.json.get('method')
        orderid = request.json.get('id')

        order = Order.query.filter_by(id=orderid).first()
        if method == 'cancel':
            order.status = 0
        elif method == 'delete':
            if order.type == 'deliver':
                deliver = Deliver.query.filter_by(orderid=order.id).first()
                db.session.delete(deliver)
            elif order.type == 'print':
                print_ = Print.query.filter_by(orderid=order.id).first()
                db.session.delete(print_)
            db.session.delete(order)
        elif method == 'accept':
            order.acc_time = datetime.now()
            order.status = 0.3
            order.eid = getEid()
        elif method == 'send':
            order.send_time = datetime.now()
            order.status = 0.7
        elif method == 'finish':
            order.sent_time = datetime.now()
            order.status = 1
        elif method == 'close':
            order.con_time = datetime.now()
            order.status = 2
            staff = Admin.query.filter_by(eid=order.eid).first()
            staff.score = staff.score + order.money

        db.session.commit()

        return {
                   'msg': '修改状态成功'
               }, 200


@admin_blueprint.route('/printdetail', methods=['GET'])
def print_detail():
    if request.method == 'GET':
        prints = Order.query.filter(Order.type == 'print', Order.status.__lt__(2)).order_by(Order.id.desc()).all()

        print_list = []
        for p in prints:
            user = User.query.filter_by(id=p.userid).first()
            print_ = Print.query.filter_by(orderid=p.id).first()
            addr = Address.query.filter_by(addindex=print_.addindex, userid=user.id).first()
            admin = Admin.query.filter_by(eid=p.eid).first()
            staff = ''
            if admin is not None:
                staff = admin.name
            print_list.append({
                'orderid': str(p.id),
                'name': user.realname,
                'userid': p.userid,
                'time': p.time.strftime('%Y年%m月%d日 %H:%M:%S'),
                'fname': print_.fname,
                'url': 'https://yiyv.miniapp.client.everdo.cn/admin/files/' + str(print_.fid),
                'count': print_.count,
                'note': print_.note,
                'addr': (addr.area + addr.addr) if print_.ziti == 0 else '',
                'money': str(p.money),
                'status': p.status,
                'staff': staff,
                'needtime': ''if print_.res_time is None else print_.res_time,
                'ziti': '是' if print_.ziti == 1 else '否',
                'station': print_.station
            })
        return {
                   'printdetail': print_list
               }, 200


@admin_blueprint.route('/deliverdetail', methods=['GET'])
def deliver_detail():
    delivers = Order.query.filter(Order.type == 'deliver', Order.status.__lt__(2)).order_by(Order.id.desc()).all()

    deliver_list = []
    for d in delivers:
        print(d.id)
        user = User.query.filter_by(id=d.userid).first()
        deliver = Deliver.query.filter_by(orderid=d.id).first()
        addr = Address.query.filter_by(addindex=deliver.addindex, userid=user.id).first()
        admin = Admin.query.filter_by(eid=d.eid).first()
        staff = ''
        if admin is not None:
            staff = admin.name
        deliver_list.append({
            'orderid': str(d.id),
            'name': user.realname,
            'userid': d.userid,
            'time': d.time.strftime('%Y年%m月%d日 %H:%M:%S'),
            'delivernum': deliver.delivernum,
            'code': deliver.code,
            'yizhan': deliver.yizhan,
            'note': deliver.note,
            'addr': addr.area + addr.addr,
            'money': str(d.money),
            'status': d.status,
            'staff': staff,
            'type': deliver.type,
            'needtime': '' if deliver.res_time is None else deliver.res_time
        })
    return {
               'deliverdetail': deliver_list
           }, 200


@admin_blueprint.route('/files/<fid>', methods=['GET'])
def get_file(fid):
    if R.get(request.args.get('token')) is None:
        return {
                   'err': 'token expired'
               }, 401
    file = File.query.filter_by(id=fid).first()
    print(file.after_name)
    print(file.origin_name)
    return send_from_directory('file/uploads', filename=file.after_name, as_attachment=True,
                               attachment_filename=file.origin_name)


@admin_blueprint.route('/serviceprice', methods=['POST', 'GET'])
def setprice():
    if request.method == 'POST':
        with open('user/money.json', 'w')as f:
            f.write(json.dumps({
                'dkd': request.json.get('dkd'),
                'zkd': request.json.get('zkd'),
                'xkd': request.json.get('xkd'),
                'ddy': request.json.get('ddy'),
                'dyps': request.json.get('dyps')
            }))
            f.close()
        return {
                   'msg': '修改成功'
               }, 200
    elif request.method == 'GET':
        with open('user/money.json', 'r')as f:
            t = f.read()
            obj = json.loads(t)
            f.close()
            return {
                       'currentprice': {
                           'dkd': obj['dkd'],
                           'zkd': obj['zkd'],
                           'xkd': obj['xkd'],
                           'ddy': obj['ddy'],
                           'dyps': obj['dyps']
                       }
                   }, 200


@admin_blueprint.route('/classtable', methods=['POST', 'GET'])
def classtable():
    if request.method == 'GET':
        objs = []
        with open('admin/classtable.json', 'r', encoding='utf-8')as f:
            objs = json.loads(f.read())
            f.close()
        return {
                   'options': objs['tables']
               }, 200
    else:
        objs = []
        with open('admin/classtable.json', 'r', encoding='utf-8')as f:
            objs = json.loads(f.read())['tables']
            f.close()
        for i in range(len(objs)):
            if request.json.get('school') == objs[i]['value']:
                objs[i]['date'] = request.json.get('time')
        with open('admin/classtable.json', 'w', encoding='utf-8')as f:
            f.write(json.dumps({
                'tables': objs
            }))
            f.close()
        return {
                   'msg': '设置' + request.json.get('school') + '的开学时间成功'
               }, 200


@admin_blueprint.route('/staffctl', methods=['GET', 'POST'])
def staffctl():
    if request.method == 'GET':
        staffs = Admin.query.all()
        staff_list = []
        for staff in staffs:
            staff_list.append({
                'eid': staff.eid,
                'ename': staff.name,
                'esex': '男' if staff.sex == 1 else '女',
                'isadmin': '是' if staff.isadmin == 1 else '否',
                'escore': staff.score
            })
        return {
                   'stafflist': staff_list
               }, 200
    else:
        admin = Admin.query.filter_by(eid=getEid()).first()
        if admin.isadmin == 0:
            return {
                'errmsg': '权限不足，非超级管理员'
            }, 201

        type = request.json.get('method')
        if type == 'add':
            name = request.json.get('name')
            sex = request.json.get('sex')
            if sex == '男':
                sex = 1
            else:
                sex = 0
            isadmin = request.json.get('isadmin')
            if isadmin:
                isadmin = 1
            else:
                isadmin = 0
            newstaff = Admin(name=name, sex=sex, password=request.json.get('pass'), isadmin=isadmin, score=0)
            db.session.add(newstaff)
            db.session.commit()
            return {
                       'msg': '添加员工成功'
                   }, 200
        elif type == 'delete':
            staff = Admin.query.filter_by(eid=request.json.get('id')).first()
            db.session.delete(staff)
            db.session.commit()
            return {
                       'msg': '删除员工成功'
                   }, 200
        elif type == 'setpass':
            staff = Admin.query.filter_by(eid=request.json.get('id')).first()
            staff.password = request.json.get('pass')
            db.session.commit()
            return {
                       'msg': '修改密码成功'
                   }, 200


@admin_blueprint.route('/staffscore', methods=['GET'])
def staffscore():
    staffs = Admin.query.order_by(Admin.score.desc()).all()
    staff_list = []
    for staff in staffs:
        staff_list.append({
            'eid': staff.eid,
            'ename': staff.name,
            'esex': '男' if staff.sex == 1 else '女',
            'escore': str(staff.score)
        })
    return {
               'staffscore': staff_list
           }, 200


@admin_blueprint.route('/logout', methods=['POST'])
def logout():
    R.delete(request.headers.get('token'))
    return {
               'msg': '账户已登出'
           }, 200


@admin_blueprint.route('/swipper', methods=['GET', 'POST'])
def swipper():
    if request.method == 'GET':
        swipers = Swiper.query.all()
        swiper_list = []
        for swiper in swipers:
            item = {
                'show': swiper.isshow == 1,
                'isact': swiper.type == 'act',
                'img': swiper.image,
                'src': swiper.src,
                'actid': '' if swiper.activity is None else swiper.activity
            }
            swiper_list.append(item)
        return {
                   'swiper_list': swiper_list
               }, 200
    elif request.method == 'POST':
        swipers = request.json
        s = Swiper.query.all()
        i = 0
        for swiper in swipers:
            if swiper['isact']:
                s[i].image = swiper['img']
                s[i].activity = swiper['actid']
                s[i].isshow = swiper['show']
                s[i].type = 'act'
            else:
                s[i].image = swiper['img']
                s[i].src = swiper['src']
                s[i].isshow = swiper['show']
                s[i].type = 'web'
            i += 1
        db.session.commit()
        return {
                   'msg': '成功'
               }, 200


@admin_blueprint.route('/activity', methods=['GET', 'POST'])
def activity():
    if request.method == 'GET':
        acts = Activity.query.all()
        act_list = []
        for act in acts:
            people_count = Checkin.query.filter_by(actid=act.id).count()
            act_list.append({
                'actid': act.id,
                'actname': act.name,
                'actdesc': act.descr,
                'actpeople': str(people_count),
                'actstatus': act.status
            })
        return {
                   'activitylist': act_list
               }, 200
    else:
        method = request.json.get('method')
        if method == 'delete':
            actid = request.json.get('id')
            acts = Activity.query.filter_by(id=actid).first()
            db.session.delete(acts)
            db.session.commit()
            return {
                       'msg': '删除活动成功'
                   }, 200
        elif method == 'add':
            act = Activity(status=1, timeline=1, subimg=1, maindesc=1)
            db.session.add(act)
            db.session.commit()
            return {
                       'msg': '创建活动成功'
                   }, 200


@admin_blueprint.route('/acteidt', methods=['GET', 'POST'])
def actedit():
    if request.method == 'GET':
        actid = request.args.get('id')
        act = Activity.query.filter_by(id=actid).first()
        return {
           'ruleform': {
               'id': act.id,
               'name': act.name if act.name is not None else '',
               'img': act.img if act.img is not None else '',
               'desc': act.descr if act.descr is not None else '',
               'date1': act.date1.strftime('%Y-%m-%d') if act.date1 is not None else '',
               'date2': act.date2.strftime('%H:%M:%S') if act.date2 is not None else '',
               'timeline': act.timeline == 1,
               'timelinedata': {
                   'time1': act.time1 if act.time1 is not None else '',
                   'desc1': act.desc1 if act.desc1 is not None else '',
                   'time2': act.time2 if act.time2 is not None else '',
                   'desc2': act.desc2 if act.desc2 is not None else '',
                   'time3': act.time3 if act.time3 is not None else '',
                   'desc3': act.desc3 if act.desc3 is not None else ''
               },
               'subimg': act.subimg == 1,
               'subimgurl': act.subimgurl if act.subimgurl is not None else '',
               'maindesc': act.maindesc == 1,
               'maindescdata': act.maindescdata if act.maindescdata is not None else '',
               'online': act.status == 0
           }
               }, 200
    else:
        actid = request.json.get('id')
        act = Activity.query.filter_by(id=actid).first()
        act.name = request.json.get('name')
        act.img = request.json.get('img')
        act.descr = request.json.get('desc')
        act.date1 = request.json.get('date1')
        act.date2 = request.json.get('date2')
        act.timeline = 1 if request.json.get('timeline') else 0
        act.desc1 = request.json.get('timelinedata')['desc1']
        act.desc2 = request.json.get('timelinedata')['desc2']
        act.desc3 = request.json.get('timelinedata')['desc3']
        act.time1 = request.json.get('timelinedata')['time1']
        act.time2 = request.json.get('timelinedata')['time2']
        act.time3 = request.json.get('timelinedata')['time3']
        act.subimg = 1 if request.json.get('subimg') else 0
        act.subimgurl = request.json.get('subimgurl')
        act.maindesc = 1 if request.json.get('maindesc') else 0
        act.maindescdata = request.json.get('maindescdata')
        act.status = 0 if request.json.get('online') else 1
        db.session.commit()
        return {
            'msg': '修改活动成功'
        }, 200


@admin_blueprint.route('/actbyid', methods=['GET'])
def actbyid():
    actid = request.args.get('id')
    chekcins = Checkin.query.filter_by(actid=actid).all()
    chekcin_list = []
    for chekcin in chekcins:
        user = User.query.get(chekcin.userid)
        chekcin_list.append({
            'id': user.id,
            'name': user.realname if user.realname is not None else '匿名',
            'nickname': user.nickName,
            'code': chekcin.code
        })
    return {
        'tabledata': chekcin_list
    }, 200


@admin_blueprint.route('/current_xq', methods=['GET', 'POST'])
def kx_date():
    if request.method == 'GET':
        d1 = ''
        d2 = ''
        with open('admin/scauzj.txt', 'r', encoding='utf-8')as f:
            d1 = f.read()
            f.close()
        with open('admin/ynnubs.txt', 'r', encoding='utf-8')as f:
            d2 = f.read()
            f.close()
        return {
            'date': [
                {
                    'school': 'scauzj',
                    'lable': '华南农业大学珠江学院',
                    'xq': d1
                },
                {
                    'school': 'ynnubs',
                    'lable': '云南师范大学商学院',
                    'xq': d2
                }
            ]
        }, 200
    else:
        school = request.json.get('school')
        xq = request.json.get('xq')
        if school == 'scauzj':
            with open('admin/scauzj.txt', 'w', encoding='utf-8')as f:
                f.write(xq)
                f.close()
            return {
                'msg': '设置scauzj成功'
            }, 200
        elif school == 'ynnubs':
            with open('admin/ynnubs.txt', 'w', encoding='utf-8')as f:
                f.write(xq)
                f.close()
            return {
                'msg': '设置ynnubs成功'
            }, 200